package androcr.client.mobile.display.cameraviewer;

import java.io.IOException;
import java.util.List;

import androcr.client.mobile.services.cameraviewer.IPreviewPresenter;
import androcr.client.mobile.services.cameraviewer.PreviewPresenter;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.Size;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class Preview extends SurfaceView implements SurfaceHolder.Callback, IPreview {
	private static final String TAG = "Preview";
	
	private IPreviewPresenter previewPresenter;
	
    private SurfaceHolder surfaceHolder;
    private Camera camera;

    private Size optimalSize;

    public Preview(Context context) {
        super(context);

        previewPresenter = new PreviewPresenter(this);
        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        surfaceHolder = getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, acquire the camera and tell it where
        // to draw.
        camera = getCamera();
        try {
        	
           camera.setPreviewDisplay(holder);
           camera.setPreviewCallback(new PreviewCallback() {
				@Override
				public void onPreviewFrame(byte[] data, Camera camera) {
						Log.d(TAG, String.valueOf(data.length));
				}});
        } catch (IOException exception) {
        	Log.e(TAG, exception.getMessage());
        	previewPresenter.releaseCamera();
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // Surface will be destroyed when we return, so stop the preview.
        // Because the CameraDevice object is not a shared resource, it's very
        // important to release it when the activity is paused.
    	previewPresenter.releaseCamera();
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        // Now that the size is known, set up the camera parameters and begin
        // the preview.
    	previewPresenter.setUpAndPreview(format, w, h);
    }

	@Override
	public Camera getCamera() {
		if (camera == null){
			camera = Camera.open();
		}
		return camera;
	}

	@Override
	public void setCamera(Camera camera) {
		this.camera = camera;
	}

	@Override
	public Size getOptimalSize() {
		return optimalSize;
	}

	@Override
	public void setOptimalSize(Size optimalSize) {
		this.optimalSize = optimalSize;
	}
	
	
}